/*
 * Copyright (c) 2023.
 *
 * 作者：bmy
 * 邮箱：2271608011@qq.com
 * gitee：https://gitee.com/bmycode
 * github：https://github.com/helpcode
 *
 */

import config, { type themeType } from "@/config";
import * as monaco from "monaco-editor";
import JsonDatabase, { type DbConfig, type themeValueType } from "@/utils/JsonDatabase";
import { themeConfig } from '@/stores/ThemeStore';
import { get } from 'svelte/store';


class ChangeTheme {
  constructor() {
    this.onThemeChanged().then()
  }

  public changeStyle(obj: themeType) {
    let key: keyof themeType;
    for (key in obj) {
      (<HTMLElement>document.querySelector("body"))
        .style.setProperty(`--${ key }`, obj[key]);
    }
  }

  public setTheme(themeName: themeValueType) {
    const themeConfig = config[themeName];
    this.changeStyle(themeConfig);
  }

  public async setThemeRunCode(conf: DbConfig, type?: string) {
    const code = async () => {
      this.setTheme(conf.theme)
      monaco.editor.setTheme(
        conf.theme == 'light' ? 'vs' : 'vs-dark'
      )
      await JsonDatabase.writeJson(conf);
    }

    // 启动时候等待1秒，等 编辑器 配置完成，再设置编辑器主题，否则 会设置失效
    type == "app"
      ? setTimeout(async () => await code(), 1000)
      : await code()
  }

  public async onThemeChanged() {
    await config.appWindow.onThemeChanged(async ({ payload: theme }) => {
      let conf = get(themeConfig)
      if (conf.autoThemeSystem) {
        conf.theme = theme
        conf.autoThemeSystem = 1
        await this.setThemeRunCode(conf)
        // update 更新，通知 App.svelte 的订阅，用于更新 ui框架 的 主题模式
        themeConfig.update(v => conf)
      }
    });
  }
}

export default new ChangeTheme